<template>
  <!-- <div class="dashboard-editor-container"> -->

    <div class="pages dashboard-editor-container" >
      <!-- <el-tabs v-model="systemData" @tab-click="refushContent">
      <el-tab-pane label="123" name="1"> <div @click="onContentClick">点击重新加载数据</div></el-tab-pane>
      <el-tab-pane label="终端首页配置" name="2"></el-tab-pane>
    </el-tabs> -->
    <div>
      <p>
          <el-button><router-link 
            type="primary"
            size="mini"
            icon="el-icon-system"
            plain
            :to="'/sysFirst'" class="link-type"
            >终端首页配置</router-link
          ></el-button>
        </p>
    </div>
    <div style="display: flex; justify-content: space-between;" >
      <Roundchart ref="round" class="echart-warpper"></Roundchart>
      <LineChart ref="line" class="echart-warpper"></LineChart>
      <LineChartSong ref="linesong" class="echart-warpper"></LineChartSong>
    </div>
    <div style="display: flex;" >
      <Memorychart ref="memory" class="echart-warpper"></Memorychart>
      <Cpuchart ref="cpu" class="echart-warpper"></Cpuchart>
      <Diskchart ref="disk" class="echart-warpper"></Diskchart>
    </div>


      <!-- 遮罩层和进度条 -->
      <div v-if="uploadProgress >= 0" class="upload-overlay" @click.prevent>
      <el-progress :percentage="uploadProgress"></el-progress>
    </div>

    <el-dialog :title="title" :visible.sync="openWarning" width="600px" append-to-body>
       <div class="dialog-body">
        检测到当前服务器有挂载USB,可能存在文件需要导入,请问是否继续进行文件导入操作?
        <!-- 检测到有鉴权成功的移动硬盘插入请点击确认按钮进行内容卡拷贝- -->
       </div>
       <div slot="footer" >
          <el-button type="primary" @click="yes">立刻导入</el-button>
          <el-button @click="no">暂时不导入</el-button>
        </div>
    </el-dialog>

     <el-dialog :title="title" :visible.sync="openDataScope" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="内容分类" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择内容分类" >
            <el-option v-for="item in tvTypeOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status == 1" ></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="文件目录">
          <el-tree
      style="max-width: 600px"
      :data="treeData"
      :props="treeProps"
      :load="loadNode"
      lazy
      show-checkbox
      ref="tree"
    ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitData">确 定</el-button>
        <el-button @click="cancelData">取 消</el-button>
      </div>
    </el-dialog>


     <!-- 上传完成提示框 -->
     <el-dialog :title="uploadSuccessTitle" :visible.sync="uploadSuccessVisible" width="500px" append-to-body>
      <div>文件上传完成,请到内容管理模块查看文件上传记录</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeUploadSuccessDialog()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import CountTo from "vue-count-to";
import { checkUsb,getFileData,getFileDataByPath,getContentType,getContentTypeData } from '@/api/index';
import { getToken } from "@/utils/auth";
import axios from "axios";
import { gecontrol } from '../api/locationMG';
import LineChart from "@/views/charts/linechart";
import LineChartSong from "@/views/charts/linechartsong";
import Roundchart from '@/views/charts/roundchart';
import Cpuchart from '@/views/charts/cpuchart';
import Diskchart from '@/views/charts/diskchart';
import Memorychart from '@/views/charts/memorychart';

export default {
  name: "Index",
  dicts: ['sys_video_type',"sys_plot_type"],
  components: {
    CountTo,
    Memorychart,
    Diskchart,
    LineChart,
    LineChartSong,
    Cpuchart,
    Roundchart
  },
  data() {
    return {
      startUploadUrl: process.env.VUE_APP_BASE_API + "/api/startUpload", // 选中文件上传地址
      uploadProgressUrl: process.env.VUE_APP_BASE_API + "/api/uploadProgress/", // 文件上传进度请求地址
      contentFileUrl: process.env.VUE_APP_BASE_API + "/api/contentFileData", // 获取上传文件数据地址
      // 版本号
      version: "3.8.9",
      timer: null, // 定时器变量
      numberRow: 2,
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf',
      },
      systemData: "1",
      uploadProgress: -1,//上传进度
      uploadTaskId: null, // 用于存储后端返回的上传任务ID
      timer: null, // 用于存储定时器ID
      selectedFiles: [], // 用于存储选中目录下的文件
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openWarning: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 内容分类选项
      tvTypeOptions: [],
      // 内容分类的类型详情选项
      tvDataOptions: [],
      tvDataFlag:false,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        fileType:[
          { required: true, message: "内容分类不能为空", trigger: "blur" }
        ],
      },
      // 上传完成提示框相关属性
      uploadSuccessTitle: "上传完成",
      uploadSuccessVisible: false,
    };
  },
  mounted() {
    // 在组件挂载后启动定时器
    this.timer = setInterval(() => {
        this.fetchData(); // 调用获取数据的方法
    }, 10000); // 每5秒执行一次5000==>10秒
  },
  created() {
    this.openFullScreen2();
    this.getContentType();
  },
  methods: {
    refushContent(tab){
      console.log("=========="+JSON.stringify(tab));
      if (tab.name === '1') {
        // 重新加载数据的逻辑
        this.getContentType(); // 调用加载数据的方法
      }
      // console.log("内容数据==========refushContent");
      // this.getContentType();
    },
    onContentClick(){
      this.getContentType(); 
    },
    getContentType(){
      getContentType().then(response =>{
        this.tvTypeOptions = response.data;
      }).catch(error => {
        console.log("获取内容分类的响应:"+error);
        return
      });

    },
    goTarget(href) {
      window.open(href, "_self");
    },
    getDataList() {
      const token = getToken();
      axios.get(this.contentFileUrl,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          var res = response.data;
            console.log("向后台获取数据:"+JSON.stringify(res));
         if (res.code == 200) {
          let memory = res.data.memory.split("%")
          let cpu = res.data.cpu.split("%")
          let disk = res.data.disk.split("%")
          let outline = res.data.onlineDevice.outline
          let online = res.data.onlineDevice.online
          let customline = res.data.onlineDevice.customline
          let dataX = []
          let dataY = []
          for (let obj of res.data.access) {
            dataX.push(obj.cat_name)
            dataY.push(obj.num)
          }
          let dataSongX = []
          let dataSongY = []
          for (let obj of res.data.accessSong) {
            dataSongX.push(obj.cat_name)
            dataSongY.push(obj.num)
          }
          this.$nextTick(() => {
            this.$refs.disk.init(disk)
            this.$refs.line.init(dataX, dataY)
            this.$refs.linesong.init(dataSongX, dataSongY)
            this.$refs.round.init(outline, online , customline)
            this.$refs.memory.init(memory)
            this.$refs.cpu.init(cpu)
          })
        } else {
          this.$message({ type: 'warning', message: res.message })
        }
        })
    },
    openFullScreen2() {
      console.log("===openFullScreen2===");
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.getDataList()
      setTimeout(() => {
        loading.close();
      }, 1000);
    },


    handleNodeClick(data, resolve ) {
      console.log("点击指定文件目录: "+data.path);
      // 点击节点时，获取当前节点的路径信息（这里假设data.path为节点路径）
      const path = data.path;
      getFileDataByPath(path).then(response => {
          console.log("获取指定文件: "+path+" 文件数据:"+JSON.stringify(response.data));
          this.selectedFiles = response.data;
        });
    },

    loadNode(node, resolve) {
      console.log("loadNode: "+node+"============"+node.level);
      //获取内容分类配置和剧情类型详情
      if (node.level === 0) {
        // 根节点请求后端获取数据
        getFileData().then(response => {
          resolve(response.data);
        });
      } else {
        console.log("模拟数据");
        const selectedNodeResultData = node.data;
        console.log("selectedNodeResultData: "+JSON.stringify(selectedNodeResultData));
        if (selectedNodeResultData &&!selectedNodeResultData.leaf) {
          const path = selectedNodeResultData.path;
          console.log("path: "+path);
          getFileDataByPath(path).then(response => {
            const children = response.data;
            resolve(children);
          });
        } else {
          resolve([]);
        }
      }
    },
    async fetchData() {
      try {
        console.log("发送定时任务检测系统是否有USB挂载");
        const response = await checkUsb(); // 调用API函数
        console.log('请求成功:', JSON.stringify(response));
        // 处理响应数据
        var data = response.data;
        console.log(JSON.stringify(data)+"======,弹框进行文件导入: "+this.openDataScope+" ,弹框提示: "+this.openWarning)
        if(data){
          //弹框展示
          if(!this.openWarning){
            this.openWarning = true;
            var row = this.numberRow;
            this.handleUpdate(row);
          }
        }else{
          //不存在或者已弹框
          this.no();
        }
      } catch (error) {
        console.error('发送定时任务,检测系统是否有挂载USB.请求失败:', error);
        // 处理错误
        this.no();
      }
    },
    beforeDestroy() {
      console.log("定时器被销毁");
    // 在组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  closeUploadSuccessDialog() {
      this.uploadSuccessVisible = false; // 隐藏上传完成提示框
  },
  no(){
    this.openWarning = false;
    this.openDataScope = false;
    this.beforeDestroy();
    console.log("销毁定时器");
  },
  yes(){
    this.openWarning = false;
    this.openDataScope = true;
    this.beforeDestroy();
  },
   // 表单重置
   reset() {
      this.form = {
        videoType: [],
        plotType: [],
        fileType: [],
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "导入USB文件";
    },
    submitData: function (){
      this.$refs["form"].validate(valid => {
        console.log("============提交校验:"+valid+"=======&&&&&&&&&&==="+JSON.stringify(this.form));
        if (valid) {
          const checkedNodes = this.$refs.tree.getCheckedNodes();
      console.log("提交信息 checkedNodes : "+JSON.stringify(checkedNodes));
      const filePaths = checkedNodes.map(node => node.path);
      console.log("提取需要上传的文件信息:"+JSON.stringify(filePaths)+"========"+filePaths.length);
      if(filePaths.length == 0){
        this.$modal.msgError("请选择上传的文件");
        return;
      }
      this.openDataScope = false;
      // this.$refs["form"].validate(valid => {
        const token = getToken();
        console.log("formData: "+JSON.stringify(filePaths)+"======="+this.form);
        var data = {
          filePaths:filePaths,
          // videoType:this.form.videoType,
          // plotType:this.form.plotType,
          fileType:this.form.fileType,
        };
        console.log("提交数据: "+JSON.stringify(data));
        // axios.post('/dev-api/api/startUpload', data , {
        axios.post(this.startUploadUrl, data , {
          headers: {
            'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
          },
        }).then(response => {
            var code = response.data.code;
            console.log("文件上传响应: "+JSON.stringify(response.data)+"==================code:"+code);
            if(code == 200){
              this.uploadTaskId = response.data.data;
              document.body.style.overflow = 'hidden'; // 禁用页面滚动
              this.timer = setInterval(() => {
                console.log("启动定时器");
                this.getUploadProgress();
              }, 1000);
            }else{
                this.$modal.msgError(JSON.stringify(response.data.msg));
                this.uploadProgress = -1;
            }
        }).catch(error => {
            console.error('上传失败', error);
            this.uploadProgress = -1;
        });
      // });


        }
      });

    },
    cancelData: function(){
      console.log("文件上传取消");
      this.openDataScope = false;
      this.reset();
    },
    getUploadProgress() {
      // console.log("getUploadProgress uploadTaskId: "+this.uploadTaskId);
      const token = getToken();
     // axios.get(`/dev-api/api/uploadProgress/${this.uploadTaskId}`,{
     axios.get(this.uploadProgressUrl+`${this.uploadTaskId}`,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          this.uploadProgress = response.data.progress;
          console.log("进度条: "+this.uploadProgress+"==========="+response.data.total);
          if (response.data.progress === 100) {
            clearInterval(this.timer);
            this.openDataScope = false;
            document.body.style.overflow = 'auto'; // 恢复页面滚动
            this.uploadProgress = -1; // 重置上传进度，隐藏遮罩层
            this.uploadSuccessVisible = true; // 显示上传完成提示框
          }
        })
        .catch(error => {
          console.error('获取上传进度失败', error);
        });
      }
   },
  }
</script>


<style scoped>
/* 遮罩层样式 */
.upload-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保遮罩层在最上层 */
}

/* 进度条样式 */
.upload-overlay .el-progress {
  width: 50%; /* 进度条宽度 */
}
</style>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 30px;
  margin-top: -20px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 30px;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>

<style lang="scss" scoped>

.default-scrollbar {
  width: 100%;
  height: 100%;
}
.flex-scrollbar {
  width: auto;
  height: auto;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
}
.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 20px;
    width: 25%;
    margin-left: -5px;
    // background-color: blur;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #fff;
    background: #fff;
    background-color: #17a0f0;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    // border-color: rgba(0, 0, 0, 0.05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-shopping {
        background: #34bfa3;
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-shopping {
      color: #34bfa3;
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .card-panel-description {
      float: center;
      font-weight: bold;
      margin: 26px;
      margin-left: 60px;

      .card-panel-text {
        line-height: 18px;
        color: #fff;
        font-size: 14px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}

@media (max-width: 550px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>
<style scoped>
.pages {
  margin: 0 auto;
  border-radius: 10px;
  box-shadow: 0px 10px 20px rgba(156, 23, 23, 0.3);
  /* width: 1400px; */
  padding: 20px 0 20px 20px;
}
.echart-warpper {
  background: rgba(255, 255, 255, .3);
  margin: 0 20px 20px 0;
  padding: 15px;
}
</style>
